package data

import (
	"context"
	"fmt"
	"helloworld/app/user/service/internal/biz"
	"helloworld/app/user/service/internal/model"
	"time"

	"github.com/go-kratos/kratos/v2/log"
	amqp "github.com/rabbitmq/amqp091-go"
	"go.mongodb.org/mongo-driver/mongo"
)

type userRepo struct {
	data *Data
	log  *log.Helper
}

// NewUserRepo .
func NewUserRepo(data *Data, logger log.Logger) biz.UserRepo {
	return &userRepo{
		data: data,
		log:  log.NewHelper(logger),
	}
}

func (r *userRepo) Save(ctx context.Context, g *biz.User) (*biz.User, error) {
	var user model.User
	r.data.mysql.First(&user)
	fmt.Printf("%v", user)
	coll := r.data.mongo.Database("test").Collection("a")
	var result model.Anaimal
	coll.FindOne(context.TODO(), model.Anaimal{Title: "a"}).Decode(&result)
	fmt.Printf("%v", result)
	rescoll := r.data.mongo.Database("sample_restaurants").Collection("restaurants")
	newRestaurant := model.Restaurant{Name: "8282", Cuisine: "Korean"}
	var resRes *mongo.InsertOneResult
	resRes, err := rescoll.InsertOne(context.TODO(), newRestaurant)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%v", resRes)
	return g, nil
}
func failOnError(err error, msg string) {
	if err != nil {
		fmt.Printf("%s: %s", msg, err)
	}
}

func (r *userRepo) Send(ctx context.Context) (*biz.User, error) {
	ch, err := r.data.mq.Channel()
	failOnError(err, "Failed to open a channel")
	q, err := ch.QueueDeclare(
		"hello", // name
		false,   // durable
		false,   // delete when unused
		false,   // exclusive
		false,   // no-wait
		nil,     // arguments
	)
	failOnError(err, "Failed to declare a queue")
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	body := "Hello World!"
	err = ch.PublishWithContext(ctx,
		"",     // exchange
		q.Name, // routing key
		false,  // mandatory
		false,  // immediate
		amqp.Publishing{
			ContentType: "text/plain",
			Body:        []byte(body),
		})
	failOnError(err, "Failed to publish a message")
	fmt.Printf(" [x] Sent %s\n", body)
	return &biz.User{Hello: "发送成功"}, nil
}
func (r *userRepo) Receive(ctx context.Context) (*biz.User, error) {
	ch, err := r.data.mq.Channel()
	failOnError(err, "Failed to open a channel")
	q, err := ch.QueueDeclare(
		"hello", // name
		false,   // durable
		false,   // delete when unused
		false,   // exclusive
		false,   // no-wait
		nil,     // arguments
	)
	failOnError(err, "Failed to declare a queue")
	msgs, err := ch.Consume(
		q.Name, // queue
		"",     // consumer
		true,   // auto-ack
		false,  // exclusive
		false,  // no-local
		false,  // no-wait
		nil,    // args
	)
	failOnError(err, "Failed to register a consumer")
	select {
	case d := <-msgs:
		fmt.Printf("Received a message: %s", d.Body)
	case <-time.After(5 * time.Second): // 等待消息的超时时间
		fmt.Println("No message received")
	}
	return &biz.User{Hello: "发送成功"}, nil
}
